#include "Component.h"


	Component::Component(const CompName name) 
		: m_manager(0),
		m_ownerId(ObjectName(-1)),
		m_name(name),
		m_valid(true)
	{
		static CompId IdCounter = 0;
		m_id = ++IdCounter;
	}

	Component::~Component() 
	{
	}
	
	void Component::AddLocalComponent(const CompPtr& comp) 
	{
		m_manager->AddComponent(GetOwnerId(), comp);
	}

	void Component::AddComponent(const ObjectName objId, const CompPtr& comp) 
	{
		m_manager->AddComponent(objId, comp);
	}
	
	void Component::DestoryComponent()
	{
		m_manager->DestoryComponent(m_name,m_id);
	}

	void Component::RequestMessage(const MsgId& message, MessageFunction f, bool local=false) 
	{
		RegisteredComponent reg(m_id,f);

		ComponentRequest req(REQ_MESSAGE,message);

		if(!local)
			m_manager->RegisterGlobalRequest(req, reg);
		else
			m_manager->RegisterLocalRequest(req,reg);
	}

	void Component::RequestComponent(const CompName& name, MessageFunction f, bool local=false) 
	{

		RegisteredComponent reg(m_id,f);

		ComponentRequest req(REQ_COMPONENT,name);

		if (!local) 
			m_manager->RegisterGlobalRequest(req, reg);
		else
			m_manager->RegisterLocalRequest(req, reg);
	}

	void Component::SendMessage(const MsgId& msg, const boost::any payload) 
	{
		if(m_manager==NULL)
			EXCEPTION("Component has not added to Manager")
		m_manager->SendGlobalMessage(REQ_MSG(msg),MSG_INFO(m_id,payload));
	}

	void Component::SendMessageToObject(const ObjectName& id, const MsgId& msg, boost::any payload) 
	{
		if(m_manager==NULL)
			EXCEPTION("Component has not added to Manager")
		m_manager->SendMessageToObject(REQ_MSG(msg),MSG_INFO(m_id,payload), id);
	}

	void Component::SendLocalMessage(const MsgId& msg, boost::any payload) 
	{
		if(m_manager==NULL)
			EXCEPTION("Component has not added to Manager")
		m_manager->SendMessageToObject(REQ_MSG(msg),MSG_INFO(m_id,payload), m_ownerId);
	}

	ObjectName Component::GetOwnerId() const
	{
		return m_ownerId;
	}

	CompName Component::GetName() const
	{
		return m_name;
	}

	void Component::setOwner(const ObjectName id) {

		m_ownerId = id;
	}

	CompId Component::GetId() const
	{
		return m_id;
	}

	bool Component::IsValid() const
	{
		return m_valid;
	}
	
#ifdef _DEBUG
	stringstream Component::Dump()
	{
		return stringstream("");
	}
#endif
